package com.qqtech.qquan.circle.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.circle.enums.CircleAuditStatusEnum;
import com.qqtech.qquan.circle.enums.CircleBaseStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleBaseTypeDictEnum;
import com.qqtech.qquan.circle.enums.CircleConst;
import com.qqtech.qquan.circle.enums.CircleFuncTypeDictEnum;
import com.qqtech.qquan.circle.enums.CircleOpenLevelDictEnum;
import com.qqtech.qquan.circle.enums.CircleZoneLevelDictEnum;
import com.qqtech.qquan.circle.model.CircleBase;
import com.qqtech.qquan.circle.model.CircleBaseQuery;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.model.CircleInfoVo;
import com.qqtech.qquan.circle.model.CircleMemberQuery;
import com.qqtech.qquan.circle.model.CircleMemberVo;
import com.qqtech.qquan.circle.model.CircleSysDict;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.circle.service.CircleCategoryService;
import com.qqtech.qquan.circle.service.CircleInfoService;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.circle.service.CircleSignService;
import com.qqtech.qquan.circle.service.CircleSysDictService;
import com.qqtech.qquan.circle.service.CircleTopicService;
import com.qqtech.qquan.community.model.CommunityBase;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.im.model.ImGroupVo;
import com.qqtech.qquan.im.service.ImGroupService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.user.enums.UserConst;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/circle/base")
public class CircleBaseController extends BaseWebController<CircleBase, CircleBaseQuery> {
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private CircleSignService circleSignService;
	@Resource
	private CircleCategoryService circleCategoryService;
	@Resource
	private CommunityBaseService communityBaseService;
	@Resource
	private CircleBaseService circleBaseService;
	@Resource
	private CircleInfoService circleInfoService;
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private CircleSysDictService circleSysDictService;
	@Resource
	private CommunityJoinService communityJoinService;
	@Resource
	private ImGroupService imGroupService;
	@Resource
	private CircleTopicService circleTopicService;

	@Override
	protected BaseService<CircleBase> getBaseService() {
		return circleBaseService;
	}

	/**
	 * 圈子详情
	 * 
	 * @param circleQuery
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		Integer circleId = circleQuery.getId();// 前端-参数
		boolean canManage = false;
		CircleMemberVo circleMemberVo = new CircleMemberVo();
		if (circleId == null) {
			result.addErr("圈子Id信息为空！");
			return result;
		}
		CircleBaseVo circleBaseVo = circleBaseService.getById(circleId);
		if (circleBaseVo == null) {
			result.addErr("找不到该圈子！");
			return result;
		} else if (circleBaseVo.getStatus() != CircleBaseStatusDictEnum.NORMAL.getCode()) {
			result.addErr("该圈子已不存在【已删除或已解散】！");
			return result;
		} else {
			circleInfoService.increasePv(circleId);// 增加点击数
			Integer circleCreatorId = circleBaseVo.getCreatorId();
			UserBaseVo userVo = userBaseService.getById(circleCreatorId);
			if (userVo != null) {
				circleBaseVo.setCreatorName(userVo.getNick());// 圈主-呢称
			} else {
				circleBaseVo.setCreatorName("未知用户");
			}
			if (circleBaseVo.getIsOfficial()) {
				circleBaseVo.setCreatorName("系统管理员");
			}
			if (!super.isVisitor()) {
				boolean isCircleMember = false;
				boolean isCircleBlackMember = false;// 是否已被圈主列为黑名单
				Integer curUserId = super.getUserId();// 当前用户id
				circleMemberVo = circleMemberService.getCircleMember(curUserId, circleId);// 这里只查询一次该成员信息
				if (circleMemberVo != null) {
					result.put("circleMemberVo", circleMemberVo);// 加入记录
					isCircleMember = true;
					if (circleMemberVo.isCircleManager() || circleMemberVo.isCircleCreator()) {
						canManage = true;
					}
					if (circleMemberVo.isBlack()) {
						isCircleBlackMember = true;
						canManage = false;
					}
				}
				if (!isCircleMember && !circleBaseVo.getIsOfficial() && !circleBaseVo.isPrivate()) {
					circleBaseVo.setCanJion(true);
				} else {
					circleBaseVo.setCanJion(false);
				}
				if ((!circleBaseVo.isGroupChat() && isCircleMember && !isCircleBlackMember)
						|| circleBaseVo.getIsOfficial()) {
					// 官方圈子：不用加入就可以发布话题
					// 非官方圈子： 只有成员才可以发布话题
					circleBaseVo.setCanAddTopic(true);
				} else {
					circleBaseVo.setCanAddTopic(false);
				}
				if (isCircleMember && !circleBaseVo.getIsOfficial() && !circleBaseVo.isTopicOnly()) {
					circleBaseVo.setCanChat(true);
				} else {
					circleBaseVo.setCanChat(false);
				}

				if (isCircleMember && !circleSignService.isSignToday(curUserId, circleId)) {
					circleBaseVo.setCanSign(true);
				} else {
					circleBaseVo.setCanSign(false);
				}
			}

			List<CircleMemberVo> members = circleMemberService.queryPartOfCircleFullMember(circleId);// 返回前8个成员
			List<String> membersImgList = Lists.newArrayList();
			if (members != null && members.size() > 0) {
				for (CircleMemberVo memberVo : members) {
					membersImgList.add(memberVo.getMemberImg());
				}
			}
			String membersImgString = StringUtil.join(membersImgList, ";");
			circleBaseVo.setImgString(membersImgString, SysConst.IMG_POSTFIX);// 成员头象
			result.put("canManage", canManage);// 是否可以管理这个圈子
			result.put("circleBase", circleBaseVo);
		}
		return result;
	}

	/**
	 * 该圈子是否只是群聊（只能聊天）
	 * 
	 * @param circleQuery
	 * @return
	 */
	@RequestMapping(value = "/isGroupChat")
	@ResponseBody
	public Result isGroupChat(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		Integer circleId = circleQuery.getId();// 前端-参数
		if (circleId == null) {
			result.addErr("圈子Id信息为空！");
			return result;
		}
		CircleBaseVo circleBaseVo = circleBaseService.getById(circleId);
		if (circleBaseVo == null) {
			result.addErr("找不到该圈子！");
			return result;
		} else if (circleBaseVo.getStatus() != CircleBaseStatusDictEnum.NORMAL.getCode()) {
			result.addErr("该圈子已不存在【已删除或已解散】！");
			return result;
		} else {
			result.put("isGroupChat", circleBaseVo.isGroupChat());
		}
		return result;
	}

	/**
	 * 详情-用于管理
	 * 
	 * @param circleQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/detail4manage")
	@ResponseBody
	public Result detail4manage(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		Integer circleId = circleQuery.getId();// 前端-参数
		if (circleId == null) {
			result.addErr("圈子Id信息为空！");
			return result;
		}
		CircleBaseVo circleBaseVo = circleBaseService.getById(circleId);
		if (circleBaseVo == null) {
			result.addErr("找不到该圈子！");
			return result;
		} else if (circleBaseVo.getStatus() != CircleBaseStatusDictEnum.NORMAL.getCode()) {
			result.addErr("该圈子已不存在【已删除或已解散】！");
			return result;
		}
		String openLevelName = circleSysDictService.dictValue(CircleConst.DICTYPE_CIRCLE_OPEN_LEVEL,
				String.valueOf(circleBaseVo.getOpenLevel()));
		circleBaseVo.setOpenLevelName(openLevelName);
		result.put("circleBase", circleBaseVo);

		if (circleId != null) {
			ImGroupVo imGroup = imGroupService.getByGroupId(circleId);
			result.put("imGroup", imGroup);
		}
		return result;
	}

	/**
	 * 圈子（搜索）
	 * 
	 * @param circleQuery
	 *            {page:page}
	 * @return
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public Result search(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> page = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : page) {
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		result.put("page", page);
		return result;
	}

	/**
	 * 更多圈子（不包括：官方圈子、我的圈子、私密圈子）
	 * 
	 * @param circleQuery
	 * @return
	 */
	@RequestMapping(value = "/more")
	@ResponseBody
	public Result more(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		List<Integer> excludeCircleIds = getRecommendCircleIds4ShowInIndex();// 不包括主页中显示的热门圈子
		if (!super.isVisitor()) {
			Integer curUserId = super.getUserId();// 当前用户id
			CircleMemberQuery query = new CircleMemberQuery();
			query.setMemberId(curUserId);
			List<Integer> myCircleIds = circleMemberService.queryMyCircleIds(query);// 我的圈子ids
			if (myCircleIds != null && myCircleIds.size() > 0) {
				excludeCircleIds.addAll(myCircleIds);// 不包括我的圈子
			}
		}
		if (excludeCircleIds != null && excludeCircleIds.size() > 0) {
			circleQuery.setExcludeCircleIds(excludeCircleIds);// 排除圈子ids
		}

		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> circlePage = circleBaseService.queryPageList(circleQuery, pageKit);
		List<CircleBaseVo> circleList = circlePage.getContent();
		if (circleList != null && circleList.size() > 0) {
			for (CircleBaseVo circleVo : circleList) {
				if (!super.isVisitor()) {
					circleVo.setCanJion(true);
				}
			}
		}

		result.put("circlePage", circlePage);
		return result;
	}

	/**
	 * 更多圈子
	 * 
	 * @param circleQuery
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Result list(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		Integer communityId = circleQuery.getCommunityId();
		if (communityId != null) {
			CommunityBase communityBase = communityBaseService.getById(communityId);
			if (communityBase != null && communityBase.getCityId() != null
					&& communityBase.getCityId().intValue() != 0) {
				circleQuery.setCityId(communityBase.getCityId());
			} else {
				circleQuery.setCityId(null);
			}
		}
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);
		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.ASC, "recommendOidx"),
				new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> circlePage = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : circlePage) {
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		result.put("circlePage", circlePage);
		return result;
	}

	/**
	 * 一个社区的圈子列表
	 * 
	 * @param circleQuery
	 * @return
	 */
	@RequestMapping(value = "/list4Community")
	@ResponseBody
	public Result list4Community(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		Integer communityId = circleQuery.getCommunityId();
		if (communityId == null) {
			result.addErr("社区id为空");
			return result;
		}
		List<Integer> myCircleIds = Lists.newArrayList();
		if (!super.isVisitor() && circleQuery.getPage() == 1) {// 如果是第一页并用我已登陆
			Integer curUserId = super.getUserId();// 当前用户id
			CircleMemberQuery query = new CircleMemberQuery();
			query.setMemberId(curUserId);
			myCircleIds = circleMemberService.queryMyCircleIds(query);// 我的圈子ids
			if (myCircleIds != null && myCircleIds.size() > 0) {
				CircleBaseQuery circleQuery4my = new CircleBaseQuery();
				circleQuery4my.setCommunityId(communityId);
				circleQuery4my.setCircleIds(myCircleIds);
				circleQuery4my.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
				Pageable pageKit2 = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "id"));
				List<CircleBaseVo> myJionCircles = circleBaseService.queryList(circleQuery4my, pageKit2);
				CircleInfoVo circleInfoVoTemp = null;
				for (CircleBaseVo circleBaseVo : myJionCircles) {
					circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
					if (circleInfoVoTemp != null) {
						circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
					} else {
						circleBaseVo.setMemberCount(0);
					}
				}
				result.put("myJionCircles", myJionCircles);// 我在这个社区的圈子中加入的圈子
			}
		}
		CommunityBase communityBase = communityBaseService.getById(communityId);
		if (communityBase != null && communityBase.getCityId() != null && communityBase.getCityId().intValue() != 0) {
			circleQuery.setCityId(communityBase.getCityId());
		} else {
			circleQuery.setCityId(null);
		}
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);// 只显示（公开或半开放的圈子）
		if (myCircleIds != null && myCircleIds.size() > 0) {
			circleQuery.setExcludeCircleIds(myCircleIds);// 分页显示的圈子中不包括“我加入的圈子”
		}
		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> page = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : page) {
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}

		result.put("page", page);
		return result;
	}

	/**
	 * 圈子主页 返回官方圈子和我的圈子
	 * 
	 * @param circleQuery
	 *            {page:page}
	 * @return
	 */
	@RequestMapping(value = "/index")
	@ResponseBody
	public Result index(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		List<CircleBaseVo> myCircleList = Lists.newArrayList();// 我的圈子
		List<CircleBaseVo> recommendCircleList = Lists.newArrayList();// 推荐的圈子（除了官方圈子之外的系统推荐的圈子）

		recommendCircleList = getRecommendCircleList4ShowInIndex();
		if (recommendCircleList != null && recommendCircleList.size() > 0) {
			for (CircleBaseVo circleVo : recommendCircleList) {
				// 完整的分类名称
				circleVo.setCategoryName(circleCategoryService.queryParentName(circleVo.getCategoryId()));
			}
		}

		if (!super.isVisitor()) {
			Integer curUserId = super.getUserId();// 当前用户id
			CircleMemberQuery query = new CircleMemberQuery();
			query.setMemberId(curUserId);
			List<Integer> myCircleIds = circleMemberService.queryMyCircleIds(query);// 我的圈子ids
			myCircleList = circleBaseService.queryListByCircleIds(myCircleIds);
			CircleInfoVo circleInfoVoTemp = null;// 圈子临时对象
			if (myCircleList != null && myCircleList.size() > 0) {
				for (CircleBaseVo circleVo : myCircleList) {
					circleInfoVoTemp = circleInfoService.getById(circleVo.getId());
					if (circleInfoVoTemp != null) {
						circleVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
					}
					// 完整的分类名称
					circleVo.setCategoryName(circleCategoryService.queryParentName(circleVo.getCategoryId()));
				}
			}
		}
		result.put("myCircleList", myCircleList);
		result.put("recommendCircleList", recommendCircleList);
		return result;
	}

	/**
	 * 我创建的圈子列表
	 *
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myCreatedCircles")
	@ResponseBody
	public Result myCreatedCircles() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		List<CircleBaseVo> circleList = circleBaseService.queryMyCreatedCircles(curUserId);
		if (circleList != null && circleList.size() > 0) {
			for (CircleBaseVo circle : circleList) {
				circle.setShowAuditStatus(true);
			}
		}
		result.put("circleList", circleList);
		return result;
	}

	/**
	 * 我加入的圈子列表
	 *
	 * @param auth
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myJoinCircles")
	@ResponseBody
	public Result myJoinCircles() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		List<CircleBaseVo> circleList = circleBaseService.queryMyJoinCircles(curUserId);
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 我的圈子列表（包括我创建的圈子和加入的圈子）
	 *
	 * @param auth
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myCircles")
	@ResponseBody
	public Result myCircles() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		CircleMemberQuery query = new CircleMemberQuery();
		query.setMemberId(curUserId);
		List<CircleBaseVo> circleList = circleBaseService.queryMyCircles(query);
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 我的圈子列表（包括我创建的圈子和加入的圈子） 【按我发布话题的时间倒序排列】
	 * 
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myOrderlyCircles")
	@ResponseBody
	public Result myOrderlyCircles() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		List<CircleBaseVo> circleList = circleBaseService.queryMyOrderlyCircles(curUserId);// 按发布话题时间倒序
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 我的群聊列表（包括我创建的和加入的群聊）
	 *
	 * @param auth
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myGroupChats")
	@ResponseBody
	public Result myGroupChats() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		List<CircleBaseVo> circleList = circleBaseService.queryMyGroupChats(curUserId);
		if (circleList != null && circleList.size() > 0) {
			for (CircleBaseVo circle : circleList) {
				List<CircleMemberVo> memberList = circleMemberService.queryCircleFullMember(circle.getId());
				circle.setImgString(getGroupChatLogoString(memberList), UserConst.IMG_POSTFIX);
				if (memberList != null) {
					circle.setMemberCount(memberList.size());
				} else {
					circle.setMemberCount(0);
				}
			}
		}
		result.put("circleList", circleList);
		return result;

	}

	private String getGroupChatLogoString(List<CircleMemberVo> members) {
		String imgString = "";
		int count = 0;
		if (members != null && members.size() > 0) {
			for (CircleMemberVo member : members) {
				count++;
				imgString += member.getMemberImg() + ";";
				if (count >= 9) {
					break;
				}
			}
		}
		return imgString;
	}

	/**
	 * 她加入的圈子列表
	 *
	 * @param auth
	 * @return
	 */
	@RequestMapping(value = "/herJoinCircles")
	@ResponseBody
	public Result herJoinCircles(@RequestBody Map<String, String> map) {
		Result result = new Result();
		Integer herUserId = Integer.valueOf(map.get("userId"));
		List<CircleBaseVo> circleList = circleBaseService.queryMyJoinCircles(herUserId);
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 她的圈子列表（包括她创建的圈子和加入的圈子）
	 *
	 * @param auth
	 * @return
	 */
	@RequestMapping(value = "/herCircles")
	@ResponseBody
	public Result herCircles(@RequestBody Map<String, String> map) {
		Result result = new Result();
		Integer herUserId = Integer.valueOf(map.get("userId"));
		CircleMemberQuery query = new CircleMemberQuery();
		query.setMemberId(herUserId);
		List<CircleBaseVo> circleList = circleBaseService.queryMyCircles(query);
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 她的圈子列表（包括她创建的圈子和加入的圈子-公开的）
	 *
	 * @param auth
	 * @return
	 */
	@RequestMapping(value = "/herOpenCircles")
	@ResponseBody
	public Result herOpenCircles(@RequestBody Map<String, String> map) {
		Result result = new Result();
		Integer herUserId = Integer.valueOf(map.get("userId"));
		List<CircleBaseVo> circleList = circleBaseService.queryMyOpenCircles(herUserId);
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 我管理的圈子列表【包含自己创建的圈子】
	 * 
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myManageCircles")
	@ResponseBody
	public Result myManageCircles() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		List<CircleBaseVo> circleList = circleBaseService.queryMyManageCircles(curUserId);
		result.put("circleList", circleList);
		return result;

	}

	/**
	 * 创建民间圈子(全功能)
	 * 
	 * @param circle
	 *            {name:name, type:type,.......}
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create")
	@ResponseBody
	public Result create(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		circle.setCreatorId(curUserId);
		circle.setType(CircleBaseTypeDictEnum.POPULAR.getCode());// 民间
		if (validateCircle(circle, result, true)) {
			circleBaseService.addCircle(circle);
		}
		return result;
	}

	/**
	 * 创建社区圈子(全功能)
	 * 
	 * @param circle
	 *            {name:name, type:type,.......}
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create4Community")
	@ResponseBody
	public Result create4Community(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		Integer communityId = circle.getCommunityId();// 社区id
		if (communityId == null) {
			result.addErr("当前社区id为空!");
			return result;
		}
		if (!communityJoinService.isJoinCommunity(communityId, curUserId)) {
			result.addErr("你没有加入这个社区,不能在此创建圈子!");
			return result;
		}
		if (circle.getCityId() == null) {
			CommunityBaseVo community = communityBaseService.getById(communityId);
			if (community != null) {
				circle.setCityId(community.getCityId());// 补充城市id
			}
		}
		circle.setCreatorId(curUserId);
		circle.setType(CircleBaseTypeDictEnum.POPULAR.getCode());// 民间圈子
		if (validateCircle(circle, result, true)) {
			circleBaseService.addCircle(circle);
		}
		return result;
	}

	/**
	 * 
	 * @param member
	 *            [{circleId:xxx,memberId:xxx,circleId:xxx,circleId:xxx,},{},{}]
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create4chat")
	@ResponseBody
	public Result create4chat(@RequestBody Map<String, String> map) throws BizzException {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id(圈子创建人)
		String groupChatName = map.get("groupChatName").toString();
		String memberIdsString = map.get("memberIds").toString();
		String[] memberIdsArray = memberIdsString.split(";");
		List<Integer> memberIds = Lists.newArrayList();
		for (int i = 0; i < memberIdsArray.length; i++) {
			if (StringUtil.isNotBlank(memberIdsArray[i]) && curUserId != Integer.parseInt(memberIdsArray[i])) {
				memberIds.add(Integer.parseInt(memberIdsArray[i]));
			}
		}

		CircleBase circle = new CircleBase();
		circle.setType(CircleBaseTypeDictEnum.POPULAR.getCode());// 民间
		circle.setName(groupChatName);
		circle.setRemark(groupChatName);
		circle.setLogo("source://image/im/group.png");// 先定一个默认的
		circle.setCreatorId(curUserId);
		circle.setCategoryName("");

		if (validateCircle(circle, result, true)) {
			Integer circleId = circleBaseService.addCircle4Chat(circle, memberIds);
			result.put("circleId", circleId);
		}
		return result;
	}

	/**
	 * 解散-圈子
	 * 
	 * @param circleBaseQuery
	 *            {id: id}
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/dismiss")
	@ResponseBody
	public Result dismiss(@RequestBody CircleBaseQuery circleBaseQuery) {
		Result result = new Result();

		Integer circleId = circleBaseQuery.getId();
		if (circleId == null) {
			result.addErr("圈子id为空！");
			return result;
		}
		CircleBaseVo circleBaseVo = circleBaseService.getById(circleId);
		if (circleBaseVo == null) {
			result.addErr("圈子不存在");
			return result;
		}
		if (circleBaseVo.getIsOfficial()) {
			result.addErr("不能操作官方圈子");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前登陆用户 id
		if (!curUserId.equals(circleBaseVo.getCreatorId())) {
			result.addErr("您不是圈主！");
			return result;
		}
		circleBaseService.dismissCircle(circleId);
		return result;
	}

	/**
	 * 更新圈子
	 * 
	 * @param circleBaseQuery
	 *            {id: id}
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/update")
	@ResponseBody
	public Result update(@RequestBody CircleBase circleBaseNew) {
		Result result = new Result();
		if (validateCircle(circleBaseNew, result, false)) {
			Integer circleId = circleBaseNew.getId();
			CircleBase circleDB = circleBaseService.getById(circleId);
			if (circleDB == null) {
				result.addErr("圈子不存在");
				return result;
			}
			Integer curUserId = super.getUserId();// 当前登陆用户id
			if (curUserId.equals(circleDB.getCreatorId()) || circleMemberService.isCircleManager(curUserId, circleId)) {
				// 只有圈主 或 管理员 才能修改
				CircleBase updateCircle = new CircleBase();
				updateCircle.setId(circleId);
				updateCircle.setLogo(circleBaseNew.getLogo());
				updateCircle.setName(circleBaseNew.getName());
				updateCircle.setCategoryId(circleBaseNew.getCategoryId());
				updateCircle.setCategoryName(circleBaseNew.getCategoryName());
				updateCircle.setTagName(circleBaseNew.getTagName());// 标签
				String remark = circleBaseNew.getRemark();
				if (StringUtils.isNotBlank(remark)) {
					remark = remark.trim();
				}
				updateCircle.setRemark(remark);
				circleBaseService.updateById(updateCircle);
			} else {
				result.addErr("只有圈主或管理员才能修改圈子");
				return result;
			}
		}
		return result;
	}

	/**
	 * 更改群聊名称
	 * 
	 * @param circleBaseNew
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/updateName")
	@ResponseBody
	public Result updateName(@RequestBody CircleBase circleBaseNew) {
		Result result = new Result();
		Integer circleId = circleBaseNew.getId();
		CircleBase circleDB = circleBaseService.getById(circleId);
		if (circleDB == null) {
			result.addErr("群聊不存在");
			return result;
		}
		CircleBase updateCircle = new CircleBase();
		updateCircle.setId(circleId);
		updateCircle.setName(circleBaseNew.getName());
		circleBaseService.updateById(updateCircle);
		return result;
	}

	/**
	 * 
	 * @param circleBaseNew
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/updateOpenLevel")
	@ResponseBody
	public Result updateOpenLevel(@RequestBody CircleBase circleBaseNew) {
		Result result = new Result();
		Integer circleId = circleBaseNew.getId();
		CircleBase circleDB = circleBaseService.getById(circleId);
		if (circleDB == null) {
			result.addErr("圈子不存在");
			return result;
		}
		Integer openLevel = circleBaseNew.getOpenLevel();
		Integer curUserId = super.getUserId();// 当前登陆用户id
		if (curUserId.equals(circleDB.getCreatorId()) || circleMemberService.isCircleManager(curUserId, circleId)) {
			// 只有圈主 或 管理员 才能修改
			CircleBase updateCircle = new CircleBase();
			updateCircle.setId(circleId);
			updateCircle.setOpenLevel(openLevel);
			circleBaseService.updateById(updateCircle);
		} else {
			result.addErr("只有圈主或管理员才能修改圈子");
			return result;
		}
		return result;
	}

	/**
	 * 设置-所有成员不能发布投票
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/setAllMemberNoVote")
	@ResponseBody
	public Result setAllMemberNoVote(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前用户id
		if (!circleBaseService.isCircleCreator(curUserId, circleId)) {
			result.addErr("您不是圈主，无权限操作.");
			return result;
		}
		circleBaseService.updateAllMemberCanAddVote(circleId, YesNoEnum.NO);
		return result;
	}

	/**
	 * 设置-所有成员可以发布投票
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/setAllMemberCanVote")
	@ResponseBody
	public Result setAllMemberCanVote(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前用户id
		if (!circleBaseService.isCircleCreator(curUserId, circleId)) {
			result.addErr("您不是圈主，无权限操作.");
			return result;
		}
		circleBaseService.updateAllMemberCanAddVote(circleId, YesNoEnum.YES);
		return result;
	}

	/**
	 * 设置-所有成员不能发布-活动
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/setAllMemberNoActivity")
	@ResponseBody
	public Result setAllMemberNoActivity(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前用户id
		if (!circleBaseService.isCircleCreator(curUserId, circleId)) {
			result.addErr("您不是圈主，无权限操作.");
			return result;
		}
		circleBaseService.updateAllMemberCanAddActivity(circleId, YesNoEnum.NO);
		return result;
	}

	/**
	 * 设置-所有成员可以发布-活动
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/setAllMemberCanActivity")
	@ResponseBody
	public Result setAllMemberCanActivity(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前用户id
		if (!circleBaseService.isCircleCreator(curUserId, circleId)) {
			result.addErr("您不是圈主，无权限操作.");
			return result;
		}
		circleBaseService.updateAllMemberCanAddActivity(circleId, YesNoEnum.YES);
		return result;
	}

	/**
	 * 是否-全员禁止发布投票
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@RequestMapping(value = "/isNoVote")
	@ResponseBody
	public Result isNoVote(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		if (circleBaseService.isKeepAllMemberNoVote(circleId)) {
			result.put("isNoVote", true);// 全员禁止发布投票（圈主例外）
		} else {
			result.put("isNoVote", false);
		}
		return result;
	}

	/**
	 * 是否-全员禁止发布活动
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@RequestMapping(value = "/isNoActivity")
	@ResponseBody
	public Result isNoActivity(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		if (circleBaseService.isKeepAllMemberNoActivity(circleId)) {
			result.put("isNoActivity", true);// 全员禁止发布活动（圈主例外）
		} else {
			result.put("isNoActivity", false);
		}
		return result;
	}

	/**
	 * @param circle
	 * @param ret
	 * @param addMethod
	 *            是否是圈子添加操作
	 * @return
	 */
	private boolean validateCircle(CircleBase circle, Result ret, boolean addMethod) {
		if (addMethod == false && circle.getId() == null) {
			ret.addErr("圈子id为空！");
		}
		if (addMethod == true && circle.getType() == null) {
			ret.addErr("请选择圈子类型");
		}
		if (addMethod && StringUtils.isBlank(circle.getName())) {
			ret.addErr("请填写圈子名称");
		}
		if (StringUtils.isBlank(circle.getRemark())) {
			ret.addErr("请填写圈子说明");
		}
		if (StringUtils.isBlank(circle.getLogo())) {
			ret.addErr("请上传圈子图片");
		}
		return ret.checkForm();
	}

	/**
	 * 是否-显示-成员头衔
	 * 
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@RequestMapping(value = "/isShowMemberGrade")
	@ResponseBody
	public Result isShowMemberGrade(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer circleId = circle.getId();
		if (circleId == null) {
			result.addErr("圈子id为空.");
			return result;
		}
		CircleBaseVo circleVo = circleBaseService.getById(circleId);
		if (circleVo.getIsShowMemberGrade() == YesNoEnum.YES.getCode()) {
			result.put("isShowMemberGrade", true);
		} else {
			result.put("isShowMemberGrade", false);
		}
		return result;
	}

	/**
	 * 显示-成员头衔
	 * 
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/showMemberGrade")
	@ResponseBody
	public Result showMemberGrade(@RequestBody CircleBase circle) {
		Result result = new Result();
		Integer circleId = circle.getId();
		CircleBase circleDB = circleBaseService.getById(circleId);
		if (circleDB == null) {
			result.addErr("圈子不存在");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前用户id
		if (circleBaseService.isCircleCreator(curUserId, circleId)
				|| circleMemberService.isCircleManager(curUserId, circleId)) {
			circleBaseService.showMemberGrade(circleId);
		} else {
			result.addErr("无权操作！");
			return result;
		}
		return result;
	}

	/**
	 * 不显示-成员头衔
	 * 
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/hideMemberGrade")
	@ResponseBody
	public Result hideMemberGrade(@RequestBody CircleBase circle) {
		Result result = new Result();
		Integer circleId = circle.getId();
		CircleBase circleDB = circleBaseService.getById(circleId);
		if (circleDB == null) {
			result.addErr("圈子不存在");
			return result;
		}
		Integer curUserId = super.getUserId();// 当前用户id
		if (circleBaseService.isCircleCreator(curUserId, circleId)
				|| circleMemberService.isCircleManager(curUserId, circleId)) {
			circleBaseService.hideMemberGrade(circleId);
		} else {
			result.addErr("无权操作！");
			return result;
		}
		return result;
	}

	/**
	 * 详情-用于升级
	 * 
	 * @param circleQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/detail4upgrade")
	@ResponseBody
	public Result detail4upgrade(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		Integer circleId = circleQuery.getId();// 前端-参数
		if (circleId == null) {
			result.addErr("圈子Id信息为空！");
			return result;
		}
		CircleBaseVo circleBaseVo = circleBaseService.getById(circleId);
		if (circleBaseVo == null) {
			result.addErr("找不到该圈子！");
			return result;
		} else if (circleBaseVo.getStatus() != CircleBaseStatusDictEnum.NORMAL.getCode()) {
			result.addErr("该圈子已不存在【已删除或已解散】！");
			return result;
		}
		String zoneLevelName = circleSysDictService.dictValue(CircleConst.DICTYPE_CIRCLE_ZONE_LEVEL,
				String.valueOf(circleBaseVo.getZoneLevel()));
		circleBaseVo.setZoneLevelName(zoneLevelName);
		List<CircleSysDict> zoneLevelList = circleSysDictService.get(CircleConst.DICTYPE_CIRCLE_ZONE_LEVEL);
		List<CircleSysDict> toZoneLevelList = Lists.newArrayList();
		Integer curZoneLevel = circleBaseVo.getZoneLevel();// 当前区域范围

		if (zoneLevelList != null && zoneLevelList.size() > 0) {
			for (CircleSysDict zoneLevel : zoneLevelList) {
				// 如果当前是多社区模式，可以平级升级【扩展更多社区】
				if ((Integer.parseInt(zoneLevel.getCode()) > curZoneLevel)
						|| (curZoneLevel == CircleZoneLevelDictEnum.MULTI_COMMUNITY.getCode()
								&& Integer.parseInt(zoneLevel.getCode()) == curZoneLevel.intValue())) {
					zoneLevel.setId(Integer.parseInt(zoneLevel.getCode()));
					toZoneLevelList.add(zoneLevel);
				}
			}
		}
		result.put("toZoneLevelList", toZoneLevelList);// 可选择的区域范围列表[{code,name}]

		result.put("circleBase", circleBaseVo);

		return result;
	}

	/**
	 * 查询推荐的圈子列表
	 * 
	 * @return
	 */
	private List<CircleBaseVo> getRecommendCircleList4ShowInIndex() {
		CircleBaseQuery circleQuery4Recommend = new CircleBaseQuery();
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery4Recommend.setIncludeFuncTypes(includeFunctypeList);// 去掉群聊

		circleQuery4Recommend.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		circleQuery4Recommend.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery4Recommend.setIsRecommend(YesNoEnum.YES.getCode());

		Pageable pageKit4Recommend = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.ASC, "recommendOidx"));// 最后推荐的放到最前面
		List<CircleBaseVo> recommendCircleList4Index = circleBaseService.queryList(circleQuery4Recommend,
				pageKit4Recommend);
		if (recommendCircleList4Index != null) {
			int recommendCircleCount = recommendCircleList4Index.size();// 推荐的圈子数量
			if (recommendCircleCount == 5) {// 刚好是一排5个时，第五个放【更多圈子】
				return recommendCircleList4Index.subList(0, 4);// 取前4个，留一个放【更多圈子】
			} else if (recommendCircleCount >= 10) {// 两排或两排以上，第十个放【更多圈子】
				return recommendCircleList4Index.subList(0, 9);// 取前9个，留一个放【更多圈子】
			} else {
				return recommendCircleList4Index;
			}
		} else {
			return Lists.newArrayList();
		}

	}

	/**
	 * 返回主页中显示的（推荐圈子ID列表） 然后在更多圈子中不显示这些（推荐圈子）
	 * 
	 * @return
	 */
	private List<Integer> getRecommendCircleIds4ShowInIndex() {
		List<Integer> circleIds4ShowInIndex = Lists.newArrayList();
		List<CircleBaseVo> recommendCircleList4Index = getRecommendCircleList4ShowInIndex();
		if (recommendCircleList4Index != null && recommendCircleList4Index.size() > 0) {
			for (CircleBaseVo circle : recommendCircleList4Index) {
				circleIds4ShowInIndex.add(circle.getId());
			}
		}
		return circleIds4ShowInIndex;
	}

}
